// 加载数据
async function loadData () {
  const res = await axios({
    url: '/my/cate/list'
  })
  document.querySelector('tbody').innerHTML = res.data
    .map(
      v => ` <tr>
    <td>
      <div class="cell">${v.cate_name}</div>
    </td>
    <td>
      <div class="cell">${v.cate_alias}</div>
    </td>
    <td>
      <div class="cell">
      <button data-id="${v.id}" class="layui-btn layui-btn-sm layui-bg-blue btn-edit">
      修改</button
    ><button data-id="${v.id}" class="layui-btn layui-btn-sm layui-bg-red btn-delete">
      删除
    </button>
      </div>
    </td>
  </tr>`
    )
    .join('')
}

loadData()

// 找到模态框
const modal = document.querySelector('.my-dialog')
const form = document.querySelector('form')
const title = document.querySelector('.el-dialog__title')
// 添加点击事件
document.querySelector('.add').addEventListener('click', function () {
  // 每次打开对话框前清空内容
  form.reset()
  title.innerHTML = '添加文章分类'
  modal.style.display = 'block'
})

document
  .querySelector('.el-dialog__close')
  .addEventListener('click', function () {
    modal.style.display = 'none'
  })
document.querySelector('#btn-cancel').addEventListener('click', function () {
  modal.style.display = 'none'
})
// 确认的点击事件
document.querySelector('#btn-ok').addEventListener('click', async function () {
  const data = serialize(form, { hash: true })

  if (title.innerHTML === '添加文章分类') {
    await axios({
      url: '/my/cate/add',
      method: 'post',
      data
    })
    alert('新增成功')
  } else {
    await axios({
      url: '/my/cate/info',
      method: 'put',
      data
    })
    alert('修改成功')
  }
  modal.style.display = 'none'
  // 重新加载数据
  loadData()
})

// 修改
document.querySelector('tbody').addEventListener('click', async function (e) {
  if (e.target.classList.contains('btn-edit')) {
    title.innerHTML = '修改文章分类'
    // 获取内容
    const res = await axios({
      url: '/my/cate/info',
      params: { id: e.target.dataset.id }
    })

    for (const key in res.data) {
      document.querySelector(`[name=${key}]`).value = res.data[key]
    }
    modal.style.display = 'block'
  }
})

// 删除
document.querySelector('tbody').addEventListener('click', async function (e) {
  if (e.target.classList.contains('btn-delete')) {
    if (confirm('确认删除吗？')) {
      await axios({
        url: '/my/cate/del',
        method: 'delete',
        params: { id: e.target.dataset.id }
      })

      loadData()
    }
  }
})
